import React,{useContext, useEffect, useRef} from 'react';
import CacheContext from './CacheContext';
import * as cacheTypes from './cache-types';

function withKeepAlive(OldComponent, {cacheId = window.location.pathname, scroll}) {
  return function (props) {
    const {cacheStates, dispatch, mount, handleScroll} = useContext(CacheContext);
    const divRef = useRef(null);

    useEffect(() => {
      const onScroll = handleScroll.bind(null, cacheId);
      if(scroll){
        divRef.current.addEventListener('scroll', onScroll,true); //监听捕获阶段才行
        //↑ 虽然是在divRef.current上监听的, 但handleScroll接受到的event.target是divRef.current下实际滚动的那个元素
      }
      return divRef.current.removeEventListener('scroll', onScroll);
    },[handleScroll]);

    useEffect(() => {
      // debugger;
      const cacheState = cacheStates[cacheId];
      if (cacheState && cacheState.doms && cacheState.status !== cacheTypes.DESTROY) { //第二次走这里
        const doms = cacheState.doms;
        doms.forEach(dom => divRef.current.appendChild(dom));
        if(scroll){
          doms.forEach(dom => {
            if(cacheState.scrolls[dom]){
              console.log('dom:',dom);
              dom.scrollTop = cacheState.scrolls[dom];
            }
          });
        }

      } else { //第一次时走这里
        mount({cacheId, reactElement: <OldComponent {...props} dispatch={dispatch}/>})
      }

    }, [cacheStates, mount, props]);


    /*return (
      <div>
        <OldComponent/>
      </div>
    )*/
    //↑ 怎么在卸载时候保存现在加载的 ↓
    // 本组件的核心思路是
    // 我们要通过容器去创建OldComponent对应的真实DOM, 并且进行缓存
    // 即使这个OldComponent被销毁了, 缓存还可以保留
    // 以后这个OldComponent再次渲染的时候, 可以复用上次的缓存就可以了
    // id={`withKeepAlive-$cacheId{}`} 是为了让我们开发调试时看清谁是谁

    //↓
    return <div id={`withKeepAlive-${cacheId}`} ref={divRef}/>
  }
}

export default withKeepAlive;
